<?php 

include_once("util/MemcacheUtil.php");

class MysqlUtil{

	private $connect_url;

	private $connect_root;

	private $connect_password;

	private $connect_db_name;

	private $memcache_open=false;


	//构造方法
	public function __construct(){

		//读取配置文件
		$conf=include "conf/conf.php";

		$this->connect_url=$conf["mysql_connect_url"];
		$this->connect_root=$conf["mysql_connect_root"];
		$this->connect_password=$conf["mysql_connect_password"];
		$this->connect_db_name=$conf["mysql_connect_db_name"];

		//是否开启 memcache
		if(isset($conf["memcache_open"])){
			$this->memcache_open=$conf["memcache_open"];
		}
		
	}


	//定义查询方法
	function query($sql){

		$data=array();

		//如果开启数据缓存，直接从缓存中读取数据
		if($this->memcache_open){

			$data=$this->_query_from_cache($sql);

		}else{

			$data=$this->_query_from_db($sql);
		}

		return $data;

	}


	private function _query_from_cache($sql){

		//尝试从cache中获取数据
		$mem=new MemcacheUtil();

		$key=md5($sql);

		$data=$mem->get($key);

		if(empty($data)){

			$data=$this->_query_from_db($sql);

			$mem->save($key,$data);
		}

		return $data;
	}


	private function _query_from_db($sql){

		//打开数据库连接
		$con=mysql_connect($this->connect_url,$this->connect_root,$this->connect_password);

		//设置目标数据库
		mysql_select_db($this->connect_db_name,$con);

		//发送sql语句
		$result=mysql_query($sql);

		//获取执行结果
		$data=array();

		if(empty($result)) return $data;

		$i=0;

		while ($row=mysql_fetch_array($result)) {
			
			$data[$i]=$row;

			$i++;
		}

		//关闭数据库连接
		mysql_close();

		return $data;
	}


	//定义新增方法
	function add($sql){


	}


	//定义删除方法
	function delete($sql){


	}


	//定义更新方法
	function update($sql){




	}

}


 ?>